/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package youtubeproject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author adnan
 */
public class Record {

    static RecordDTO rdto = null;

    public static String getValue(String code) {
        RecordDTO r = getObject();
//        System.out.println("r.links=" + r.links.keySet());
        return r.links.get(code);
    }

//    public static void main(String[] args) {
////        Record.saveValue("TEST", "TEST1");
//        System.out.println("Record = " + getValue("TEST"));
//        System.out.println("Record = " + getValue("TESTD"));
//    }

    public static RecordDTO getObject() {
        RecordDTO o = null;
        if (rdto == null) {
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("RecordFile"));
                Object readObj = ois.readObject();
                o = (RecordDTO) readObj;
            } catch (Exception ex) {
                System.out.println("File Not Found , creating it.");
            }
            if (o == null) {
                o = new RecordDTO();
                saveObject(o);
            }
            rdto = o;
        } else {
            o = rdto;
        }
        return o;
    }

    public static void saveValue(String code, String value) {
        RecordDTO d = getObject();
        d.links.put(code, value);
        saveObject(d);
    }

    private static void saveObject(RecordDTO o) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("RecordFile"));
            oos.writeObject(o);
        } catch (Exception ex) {
            Logger.getLogger(Record.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
